package com.ruoyi.factory.costControl.common.utils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class NetworkUtils {

    /**
     * 获取客户端的内网IP地址
     */
    public static String getClientIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if ("127.0.0.1".equals(ip)) {
                // 本地测试时获取本机IP
                try {
                    ip = InetAddress.getLocalHost().getHostAddress();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
            }
        }
        return ip;
    }

    /**
     * 获取客户端的外网IP地址
     */
    public static String getClientExternalIp(HttpServletRequest request) {
        String ip = getClientIpAddr(request);
        // 处理多级反向代理的情况
        String[] ips = ip.split(",");
        for (int i = 0; i < ips.length; i++) {
            String strIp = ips[i];
            if (!("127.0.0.1".equals(strIp) || "0:0:0:0:0:0:0:1".equals(strIp))) {
                // 排除内网IP
//                boolean isInnerIp = isInnerIp(strIp);
//                if (!isInnerIp) {
//                    ip = strIp;
//                    break;
//                }
            }
        }
        return ip;
    }

    /**
     * 检查IP是否为内网IP
     */
//    public static boolean isInnerIp(String ipAddress) {
//        boolean isInnerIp;
//        long ipNum = getIpNum(ipAddress);
//        /**
//         * 私有IP范围
//         * A类 10.0.0.0-10.255.255.255
//         * B类 172.16.0.0-172.31.255.255
//         * C类 192.168.0.0-192.168.255.255
//         */
//        long aBegin = getIpNum("10.0.0.0");
//        long aEnd = getIpNum("10.255.255.255");
//        long bBegin = getIpNum("172.16.0.0");
//        long bEnd = getIpNum("172.31.255.255");
//        long cBegin = getIpNum("192.168.0.0");
//        long cEnd = getIpNum("192.168.255.255");
//        isInnerIp = isInnerIp(ipNum, aBegin, aEnd) || isInnerIp(ipNum, bBegin, bEnd) || isInnerIp(ipNum, cBegin, cEnd) || ipAddress.equals("127.0.0.1");
//        return isInnerIp;
//    }

}
